package com.gaofans.nrpc.common.serializer.jdk;

import com.gaofans.nrpc.common.exception.NRpcException;
import com.gaofans.nrpc.common.serializer.Serializer;
import com.gaofans.nrpc.common.serializer.SerializerExceptionEnum;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * jdk默认的序列化
 * @author GaoFans
 */
public class JdkSerializer implements Serializer {

    @Override
    public <T> byte[] serialize(T t) {
        try(ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(t);
            return bos.toByteArray();
        }catch (Exception e){
            throw new NRpcException(e.getCause(),SerializerExceptionEnum.SerializerException);
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        try(ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes))) {
            return (T) ois.readObject();
        }catch (Exception e){
            throw new NRpcException(e.getCause(),SerializerExceptionEnum.DeSerializerException);
        }
    }
}
